package com.hll.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {

    /**
     * 测试
     */
    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        return "ok";
    }

    /**
     * 测试thymeleaf
     */
    @RequestMapping("/thymeleaf")
    public String thymeleaf(Model model){
        //把数据存入model
        model.addAttribute("name","您可以点击登录");
        //返回test.html页面
        return "test";
    }

    /**
     * 跳转到登录页面
     */
    @RequestMapping("/goLogin")
    public String goLogin(){
        return "/login";
    }

    /**
     * 登录成功跳转查询
     */
   /* @RequestMapping("/userAll")
    public String userAll(){
        return "/user/userAll";
    }*/


    /**
     * 登录逻辑处理
     */
    @RequestMapping("/login")
    public String login(String username,String password,Model model) {
        /**
         *使用shiro编写认证操作
         */
        //1.获取subject
        Subject subject = SecurityUtils.getSubject();
        //2.封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //执行登录方法
        try {
            //没有任何异常登录成功后
            subject.login(token);
            return"redirect:/userAll";

        } catch (UnknownAccountException e) {
            e.printStackTrace();
            //有异常登录失败，UnknownAccountException用户名不存在
            model.addAttribute("msg","用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            //有异常登录失败，IncorrectCredentialsException密码错误
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }
}
